<?php
defined( '_JEXEC' ) or die( 'Restricted access' );

class igCategoryModeligCategory extends igbaseModel
{
	public $_total;
	protected $context = 'igcategory';

	function __construct()
	{
		global $mainframe;

		parent::__construct();

		$limitstart = JRequest::getInt('limitstart',0);
		$this->setState('limitstart', $limitstart);

		$id = JRequest::getInt('id', 0);
		$this->setId($id);
	}

	function setId($id)
	{
		$this->_id = (int)$id;
	}

	function getCategory()
	{
		$query = 'SELECT * FROM #__igallery WHERE id = '. (int)$this->_id;
		$this->_db->setQuery($query);
		$this->_category = $this->_db->loadObject();
		return $this->_category;
	}
	
	function getCat($id)
	{
		$query = 'SELECT * FROM #__igallery WHERE id = '. (int)$id;
		$this->_db->setQuery($query);
		$category = $this->_db->loadObject();
		return $category;
	}

	function getPagination()
	{
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->_total, $this->getState('limitstart'), $this->_profile->menu_pagination_amount );
		}

		return $this->_pagination;
	}
	
	function getThumbPagination()
	{
		if (empty($this->_thumbPagination))
		{
			jimport('joomla.html.pagination');
			$this->_thumbPagination = new JPagination( $this->_thumbTotal, JRequest::getInt('limitstart',0), $this->_profile->thumb_pagination_amount );
		}

		return $this->_thumbPagination;
	}

	function getCategoryChildren()
	{
		$user =& JFactory::getUser();

		$query = 'SELECT #__igallery.*, '.
		'#__igallery_profiles.menu_max_width, #__igallery_profiles.menu_max_height, #__igallery_profiles.img_quality '.
		'FROM #__igallery '.
		'INNER JOIN #__igallery_profiles ON #__igallery.profile = #__igallery_profiles.id '.
		'WHERE #__igallery.published = 1 AND #__igallery.moderate = 1 '.
		'AND #__igallery.parent = '.(int)$this->_category->id.
		' ORDER BY ordering';

		if($this->_profile->menu_pagination == 1)
		{
			$categoryChildren = $this->_getList($query, $this->getState('limitstart'), $this->_profile->menu_pagination_amount );
			$this->_total = $this->_getListCount($query);
		}
		else
		{
			$categoryChildren = $this->_getList($query);
			$this->_total = $this->_getListCount($query);
		}
		
		$count = count($categoryChildren);
		
		for($i=0; $i<$count; $i++ )
		{
			if( !$this->authenticate('acl_cat_menu', $categoryChildren[$i]->id, false, false) )
			{
				unset($categoryChildren[$i]);
			}
		}
		$categoryChildren = array_values($categoryChildren);
		
		$categoryChildren =& $this->getMenuImages($categoryChildren);

		return $categoryChildren;
	}
	
	function getMenuImages(&$categories)
	{
		for($i=0; $i<count($categories); $i++ )
		{
			if( empty($categories[$i]->parent) )
			{
				$profileId = $categories[$i]->profile;
			}
			else
			{
				$parentCat = $this->getCat($categories[$i]->parent);
				$profileId = $parentCat->profile;
			}
			
			$profile = $this->getProfile($profileId);
			
			
			if( strlen($categories[$i]->menu_image_filename) > 1)
			{
				$menuPhoto = new stdClass();
				$menuPhoto->filename = $categories[$i]->menu_image_filename;
				$menuPhoto->rotation = 0;
			}
			else
			{
				$query = 'SELECT * from #__igallery_img WHERE gallery_id = '.(int)$categories[$i]->id.
				' AND menu_image = 1 LIMIT 1';
				$this->_db->setQuery($query);
				$menuPhoto = $this->_db->loadObject();
				
				if(empty($menuPhoto) && $profile->menu_image_defaults == 1)
				{
					$query = 'SELECT * from #__igallery_img WHERE gallery_id = '.(int)$categories[$i]->id.
					' ORDER BY ordering LIMIT 1';
					$this->_db->setQuery($query);
					$menuPhoto = $this->_db->loadObject();
				}
			 }
				
			if( !empty($menuPhoto->filename) )
			{
				$categories[$i]->fileArray = igFileHelper::originalToResized($menuPhoto->filename, 
	            $profile->menu_max_width, $profile->menu_max_height, $profile->img_quality, $profile->crop_menu,
	            $menuPhoto->rotation, $profile->round_menu, $profile->round_fill);
	        }
			
        }
		
		return $categories;
	}
	
	function addCategoryHit()
	{
		$this->addTablePath(IG_ADMINISTRATOR_COMPONENT.DS.'tables');
		$row =& $this->getTable('igallery');
		$row->load( (int)$this->_id );
		$row->hits = $row->hits + 1;
		
		if(!$row->store())
		{
			$this->setError($this->_db->getErrorMsg());
		}
	}

	function getPhotoList()
	{
		$this->addCategoryHit();
		
		$user =& JFactory::getUser();
		$where2 = '';
		
		if(!empty($this->_tag))
		{
			$tagsArray = explode(',',$this->_tag);
			$tagsLikeSql = array();
			
			foreach($tagsArray as $key => $value)
			{
			   $tagsLikeSql[] = 'tags LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $value, true ).'%', false );
			}
			$tagClauses = implode( ' OR ', $tagsLikeSql ) ;
			$where2 = ' AND ('.$tagClauses.')';
		}
		
		
		$limit = $this->_profile->thumb_pagination == 0 ? 0 : $this->_profile->thumb_pagination_amount;

		$query = 'SELECT * FROM #__igallery_img WHERE gallery_id = '. (int)$this->_id.$where2 .
		' AND published = 1 AND moderate = 1 AND access <= '.(int)$user->get('aid', 0).' ORDER BY ordering';
		$this->_photoList = $this->_getList($query, JRequest::getInt('limitstart',0), (int)$limit);
		
		$this->_thumbTotal = $this->_getListCount($query);

		return $this->_photoList;
	}

	function getRandomList()
	{
		$user =& JFactory::getUser();

		if($this->_child)
		{
			$children = igHtmlHelper::getChildList($this->_id, 'flat');
			$children[] = (int)$this->_id;
			$where = 'FIND_IN_SET(gallery_id,"'.implode(',',$children).'")';
		}
		else
		{
			$where = 'gallery_id = '. (int)$this->_id;
		}
		
		$where2 = '';
		
		if(!empty($this->_tag))
		{
			$tagsArray = explode(',',$this->_tag);
			$tagsLikeSql = array();
			
			foreach($tagsArray as $key => $value)
			{
			   $tagsLikeSql[] = 'tags LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $value, true ).'%', false );
			}
			$tagClauses = implode( ' OR ', $tagsLikeSql ) ;
			$where2 = ' AND ('.$tagClauses.')';
		}

		$query = 'SELECT DISTINCT *'
		.   ' FROM #__igallery_img'
		.   ' WHERE '.$where.$where2
		.   ' AND published = 1 AND moderate = 1'
		.   ' AND access <= '.(int)$user->get('aid', 0)
		.   ' ORDER BY RAND()';
		
		$limit = $this->_profile->thumb_pagination == 0 ? (int)$this->_limit : $this->_profile->thumb_pagination_amount;
		$this->_photoList = $this->_getList($query, JRequest::getInt('limitstart',0), (int)$limit);
		
		$this->_thumbTotal = $this->_getListCount($query);
		
		return $this->_photoList;
	}

	function getLatestList()
	{
		$user =& JFactory::getUser();

		if($this->_child)
		{
			$children = igHtmlHelper::getChildList($this->_id, 'flat');
			$children[] = (int)$this->_id;
			$where = 'FIND_IN_SET(gallery_id,"'.implode(',',$children).'")';
		}
		else
		{
			$where = 'gallery_id = '. (int)$this->_id;
		}
		
		$where2 = '';
		
		if(!empty($this->_tag))
		{
			$tagsArray = explode(',',$this->_tag);
			$tagsLikeSql = array();
			
			foreach($tagsArray as $key => $value)
			{
			   $tagsLikeSql[] = 'tags LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $value, true ).'%', false );
			}
			$tagClauses = implode( ' OR ', $tagsLikeSql ) ;
			$where2 = ' AND ('.$tagClauses.')';
		}

		$query = 'SELECT *'
		.   ' FROM #__igallery_img'
		.   ' WHERE '.$where.$where2
		.   ' AND published = 1 AND moderate = 1'
		.   ' AND access <= '.(int)$user->get('aid', 0)
		.   ' ORDER BY date DESC';
		
		$limit = $this->_profile->thumb_pagination == 0 ? $this->_limit : $this->_profile->thumb_pagination_amount;
		$this->_photoList = $this->_getList($query, JRequest::getInt('limitstart',0), (int)$limit);
		
		$this->_thumbTotal = $this->_getListCount($query);
		return $this->_photoList;
	}

	function getRatedList()
	{
		$user =& JFactory::getUser();

		if($this->_child)
		{
			$children = igHtmlHelper::getChildList($this->_id, 'flat');
			$children[] = (int)$this->_id;
			$where = 'FIND_IN_SET(r.gallery_id,"'.implode(',',$children).'")';
		}
		else
		{
			$where = 'r.gallery_id = '. (int)$this->_id;
		}
		
		$where2 = '';
		
		if(!empty($this->_tag))
		{
			$tagsArray = explode(',',$this->_tag);
			$tagsLikeSql = array();
			
			foreach($tagsArray as $key => $value)
			{
			   $tagsLikeSql[] = 'tags LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $value, true ).'%', false );
			}
			$tagClauses = implode( ' OR ', $tagsLikeSql ) ;
			$where2 = ' AND ('.$tagClauses.')';
		}

		$query = 'SELECT i.*, SUM(rating) AS rating'
		.   ' FROM #__igallery_img AS i'
		.   ' LEFT JOIN #__igallery_rating AS r ON i.id = r.img_id'
		.   ' WHERE '.$where.$where2
		.   ' AND i.published = 1 AND r.published = 1 AND i.moderate = 1'
		.   ' AND i.access <= '.(int)$user->get('aid', 0)
		.   ' GROUP BY r.img_id'
		.   ' ORDER BY rating DESC';
		
		$limit = $this->_profile->thumb_pagination == 0 ? $this->_limit : $this->_profile->thumb_pagination_amount;
		$this->_photoList = $this->_getList($query, JRequest::getInt('limitstart',0), (int)$limit);

		$this->_thumbTotal = $this->_getListCount($query);
		return $this->_photoList;
	}

	function getCommentedList()
	{
		$user =& JFactory::getUser();

		if($this->_child)
		{
			$children = igHtmlHelper::getChildList($this->_id, 'flat');
			$children[] = (int)$this->_id;
			$where = 'FIND_IN_SET(c.gallery_id,"'.implode(',',$children).'")';
		}
		else
		{
			$where = 'c.gallery_id = '. (int)$this->_id;
		}
		
		$where2 = '';
		
		if(!empty($this->_tag))
		{
			$tagsArray = explode(',',$this->_tag);
			$tagsLikeSql = array();
			
			foreach($tagsArray as $key => $value)
			{
			   $tagsLikeSql[] = 'tags LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $value, true ).'%', false );
			}
			$tagClauses = implode( ' OR ', $tagsLikeSql ) ;
			$where2 = ' AND ('.$tagClauses.')';
		}

		$query = 'SELECT i.*, COUNT(*) as total'
		.   ' FROM #__igallery_img AS i'
		.   ' LEFT JOIN #__igallery_comments AS c ON i.id = c.img_id'
		.   ' WHERE '.$where.$where2
		.   ' AND i.published = 1 AND c.moderate = 1'
		.   ' AND i.access <= '.(int)$user->get('aid', 0)
		.   ' GROUP BY c.img_id'
		.   ' ORDER BY total DESC';
		
		$limit = $this->_profile->thumb_pagination == 0 ? $this->_limit : $this->_profile->thumb_pagination_amount;
		$this->_photoList = $this->_getList($query, JRequest::getInt('limitstart',0), (int)$limit);
		
		$this->_thumbTotal = $this->_getListCount($query);
		return $this->_photoList;
	}

	function getTaggedList()
	{
		$user =& JFactory::getUser();

		if($this->_child)
		{
			$children = igHtmlHelper::getChildList($this->_id, 'flat');
			$children[] = (int)$this->_id;
			$where = 'FIND_IN_SET(gallery_id,"'.implode(',',$children).'")';
		}
		else
		{
			$where = 'gallery_id = '. (int)$this->_id;
		}

		$tagsArray = explode(',',$this->_tag);
		$tagsLikeSql = array();
		foreach($tagsArray as $key => $value)
		{
			$tagsLikeSql[] = 'tags LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $value, true ).'%', false );
		}
		$tagClauses = implode( ' OR ', $tagsLikeSql ) ;
		$where2 = '('.$tagClauses.')';

		$query = 'SELECT *'
		.   ' FROM #__igallery_img'
		.   ' WHERE '.$where
		.   ' AND '.$where2
		.   ' AND published = 1 AND moderate = 1'
		.   ' AND access <= '.(int)$user->get('aid', 0)
		.   ' ORDER BY ordering';
		
		$limit = $this->_profile->thumb_pagination == 0 ? $this->_limit : $this->_profile->thumb_pagination_amount;
		$this->_photoList = $this->_getList($query, JRequest::getInt('limitstart',0), (int)$limit);

		$this->_thumbTotal = $this->_getListCount($query);
		return $this->_photoList;
	}

	function getCommentsList()
	{
		$user =& JFactory::getUser();

		JArrayHelper::toInteger($this->_photoListIds);
		$idSet = implode(',',$this->_photoListIds);

		$query = 'SELECT i.id,c.img_id,c.text,c.date,c.author'
		.   ' FROM #__igallery_img AS i'
		.   ' INNER JOIN #__igallery_comments AS c ON i.id = c.img_id'
		.   ' WHERE i.access <= '.(int)$user->get('aid', 0)
		.   ' AND FIND_IN_SET(c.img_id,"'.$idSet.'")'
		.   ' AND i.published =1  AND c.moderate = 1'
		.   ' AND c.published =1'
		.   ' ORDER BY c.date';

		$commentsList = $this->_getList($query);
		return $commentsList;
	}

	function getRatingsList()
	{
		$user =& JFactory::getUser();
		JArrayHelper::toInteger($this->_photoListIds);
		$idSet = implode(',',$this->_photoListIds);

		$query = 'SELECT i.id, r.img_id, r.rating, r.author'
		.   ' FROM #__igallery_img AS i'
		.   ' INNER JOIN #__igallery_rating AS r ON i.id = r.img_id'
		.   ' WHERE i.access <= '.(int)$user->get('aid', 0)
		.   ' AND FIND_IN_SET(r.img_id,"'.$idSet.'")'
		.   ' AND i.published =1  AND i.moderate = 1'
		.   ' AND r.published =1';

		$ratingsList = $this->_getList($query);

		return $ratingsList;
	}

	function getHitsList()
	{
		$user =& JFactory::getUser();

		if($this->_child)
		{
			$children = igHtmlHelper::getChildList($this->_id, 'flat');
			$children[] = (int)$this->_id;
			$where = 'FIND_IN_SET(gallery_id,"'.implode(',',$children).'")';
		}
		else
		{
			$where = 'gallery_id = '. (int)$this->_id;
		}
		
		$where2 = '';
		
		if(!empty($this->_tag))
		{
			$tagsArray = explode(',',$this->_tag);
			$tagsLikeSql = array();
			
			foreach($tagsArray as $key => $value)
			{
			   $tagsLikeSql[] = 'tags LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $value, true ).'%', false );
			}
			$tagClauses = implode( ' OR ', $tagsLikeSql ) ;
			$where2 = ' AND ('.$tagClauses.')';
		}

		$query = 'SELECT *'
		.   ' FROM #__igallery_img'
		.   ' WHERE '.$where.$where2
		.   ' AND published = 1 AND moderate = 1'
		.   ' AND access <= '.(int)$user->get('aid', 0)
		.   ' ORDER BY hits DESC';
		
		$limit = $this->_profile->thumb_pagination == 0 ? $this->_limit : $this->_profile->thumb_pagination_amount;
		$this->_photoList = $this->_getList($query, JRequest::getInt('limitstart',0), (int)$limit);

		$this->_thumbTotal = $this->_getListCount($query);
		return $this->_photoList;
	}

	function add_comment()
	{
		
		$user   =& JFactory::getUser();
		$configArray =& JComponentHelper::getParams('com_igallery');
		
		$imgId  = JRequest::getInt('img_id');
		if( $user->get('guest') )
		{
			echo 0;
			return;
		}

		$query = 'SELECT '.
		'#__igallery_img.*, #__igallery.name, #__igallery_profiles.allow_comments, #__igallery_profiles.lbox_allow_comments '.
		'FROM #__igallery_img '.
		'INNER JOIN #__igallery ON #__igallery.id = #__igallery_img.gallery_id '.
		'INNER JOIN #__igallery_profiles ON #__igallery_profiles.id = #__igallery.profile '.
		'WHERE #__igallery_img.id = '. JRequest::getInt('comment_img_id',0);
		'WHERE #__igallery_img.id = '.(int)$imgId;

		$this->_db->setQuery($query);
		$photo = $this->_db->loadObject();

		if($photo->allow_comments != 1 && $photo->lbox_allow_comments != 1)
		{
			echo 'ig-restricted';
			return;
		}

		$row =& $this->getTable('igallery_comments');

		$row->gallery_id = JRequest::getInt('comment_gallery_id');
		$row->img_id = JRequest::getInt('comment_img_id');
		$row->author = $user->get('username');
		$row->ip = JFilterOutput::cleanText($_SERVER['REMOTE_ADDR']);
		$row->published = 1;
		$row->date = time();
		$row->moderate = $configArray->get('moderate_comment', 0) == 0 ? 1 : 0;

		$commentText = JRequest::getVar('comment_textarea');
		$htmlText = htmlspecialchars($commentText, ENT_QUOTES);
		$row->text = nl2br($htmlText);

		if (!$row->store())
		{
			echo $row->getError();
			return false;
		}

		$configArray =& JComponentHelper::getParams('com_igallery');
		if($configArray->get('notify_new_comment', 0) == 1)
		{
			$this->notify('comment', $row->img_id, $row->text);
		}
		
		if($configArray->get('moderate_comment', 0) == 1)
		{
			echo 'ig-moderate';
			return;
		}

		$response = $row->text.'<br /><span class="italics_text">'.$row->author.' - '.JHTML::_('date',  $row->date,  "%A, %d %B %Y %I:%M %p" ).'</span>';

		echo $response;
	}

	function add_rating()
	{
		$user =& JFactory::getUser();
		if($user->get('guest'))
		{
			echo 'ig-login';
			return;
		}

		$post	= JRequest::get('post');

		$query = 'SELECT '.
		'#__igallery_img.*, #__igallery.name, #__igallery_profiles.allow_rating, #__igallery_profiles.lbox_allow_rating '.
		'FROM #__igallery_img '.
		'INNER JOIN #__igallery ON #__igallery.id = #__igallery_img.gallery_id '.
		'INNER JOIN #__igallery_profiles ON #__igallery_profiles.id = #__igallery.profile '.
		'WHERE #__igallery_img.id = '. (int)$post['img_id'];
		$this->_db->setQuery($query);
		$photo = $this->_db->loadObject();

		if($photo->allow_rating != 1 && $photo->lbox_allow_rating != 1)
		{
			echo 'ig-restricted';
			return;
		}

		$query = 'SELECT * FROM #__igallery_rating WHERE author = \''.$this->_db->getEscaped( $user->get('username') ).'\' AND img_id = '.(int)$post['img_id'];
		$this->_db->setQuery($query);
		$this->_db->query($query);
		if($this->_db->getNumRows() != 0)
		{
			echo 'ig-already';
			return;
		}

		$row =& $this->getTable('igallery_rating');

		if (!$row->bind($post))
		{
			echo $row->getError();
			return false;
		}

		$row->ip = JFilterOutput::cleanText($_SERVER['REMOTE_ADDR']);
		$row->author = $user->get('username');
		$row->published = 1;
		$row->date = time();

		if (!$row->store())
		{
			echo $row->getError();
			return false;
		}

		$query = 'SELECT * FROM #__igallery_rating WHERE img_id = '.(int)$row->img_id;
		$this->_db->setQuery($query);
		$ratingsList = $this->_db->loadObjectList();

		$rating = 0;
		for($i=0; $i<count($ratingsList); $i++)
		{
			$rating = $rating + $ratingsList[$i]->rating;
		}
		$rating = round( ($rating/ count($ratingsList) ) * 2) /2;

		echo $rating;
	}

}